import "babel-polyfill";
import fly from './interceptor';
import template from '../lib/art-template@4.13.2';
import auth from './auth';
import {
    baseUrl,
} from './config';
import {
    addClass,
    removeClass
} from '../js/utils';

// Methods
class IndexView {
    constructor() {
        this.data = this.data();
        this.root = document.getElementById('root');
        this.welcome = document.getElementById("welcome");
        this.alertContent = document.getElementById("alertContent");
        this.alertWraper = document.getElementById("alertWraper");

        this.touch = {}; // 触摸数据
        this.timer = null; // 倒计时
        this.timeout = 30; // 倒计时30s
        this.qipao_timer = null;
    }
    data() {
        return {
            my_pigticket: [], // 用户猪符列表
            openWelcome: 0, // 标识位标识还没有打开环境弹框
        }
    }
    ready() {

        // 点击事件监听
        document.addEventListener('touchstart', (e) => {
            let target = e.target;
            // 弹窗容器关闭事件
            if (target.className.indexOf('alertclose') > -1) {
                this.alertWraper.style.display = 'none';
                if (this.data.openWelcome == 1) {
                    // 启动倒计时
                    this.clockControl(); // 启动倒计时
                    this.data.openWelcome = 2; // 标识位已经关闭 
                }
            }
            if (target.className.indexOf("point") > -1) {
                if (target.className.indexOf("point_21") > -1) {
                    this.setPigTicket(() => {
                        location.replace("./my.html");
                    })
                } else {
                    this.handleCheck(target);
                }
            }
        }, false)

        // ios微信音频自动播放
        this.audioAutoPlay("myaudio");

        // 阻止浏览器下拉事件
        function stopmove(e) {
            e.preventDefault()
        }
        document.addEventListener('touchmove', stopmove, {
            passive: false
        });

        // 监听首页触摸事件
        this.welcome.addEventListener("touchstart", welcome_touchstart, false);
        this.welcome.addEventListener("touchmove", welcome_touchmove, false);
        this.welcome.addEventListener("touchend", welcome_touchend, false);

        let that = this;

        function welcome_touchstart(e) {
            e.preventDefault();
            that.touch.startY = e.touches[0].pageY;
        }

        function welcome_touchmove(e) {
            e.preventDefault();
            that.touch.currentY = e.touches[0].pageY;
            if (that.touch.currentY - that.touch.startY > 0) return;
            let y = that.touch.currentY - that.touch.startY;
            that.welcome.style.transform = `translate3d(0,${y}px,0)`;
        }

        function welcome_touchend(e) {
            e.preventDefault();
            that.touch.endY = e.changedTouches[0].pageY;
            if (that.touch.endY - that.touch.startY > 0) return;
            if (that.touch.endY - that.touch.startY > -120) {
                that.welcome.style.transform = `translate3d(0,0,0)`; // 小于阀值距离，回弹
            } else {
                that.welcome.style.transform = `translate3d(0,-100%,0)`;
                // 移除浏览器禁止移动事件
                document.removeEventListener("touchmove", stopmove, {
                    passive: false
                });
                // 移除监听首页触摸事件
                that.welcome.removeEventListener("touchstart", welcome_touchstart, false);
                that.welcome.removeEventListener("touchmove", welcome_touchmove, false);
                that.welcome.removeEventListener("touchend", welcome_touchend, false);
                that.renderAlert({
                    className: "alertGameMiddle",
                    type: 'welcome_alert',
                    imgsrc: `${baseUrl}tk_title.png`,
                    imgsrc2: `${baseUrl}tk_paper.png`,
                    alertWord: '<h3>维达送祝福啦！</h3><p class="subtitle">游戏规则：</p><p class="content_word">限时30秒，从充满年味的庙会场景中，找出维达产品，领取福卡，集齐五福即可兑换电影票，更有维达优惠券等你来领取！分享好友可获再次挑战的机会，好友之间可转赠福卡。</p><p class="tipclose">点击右上角“X”键关闭，开始游戏</p>',
                })
            }
        }
        auth.requestConfig(); // 微信授权
    }
    renderAlert(params) {
        let html = template('welcomeAlertTmpl', params);
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
        if (params.type === 'welcome_alert') {
            this.data.openWelcome = 1; // 标志位，标识已经打开欢迎介绍弹框
            addClass(this.alertContent, "welcome_alert_conetnt");
        } else {
            removeClass(this.alertContent, "welcome_alert_conetnt");
        }
    }
    // 处理弹窗页按钮点击事件
    handleAlertClick(type) {
        if (!type) return;
        this.alertWraper.style.display = 'none';
        switch (type) {
            case 'gameover':
                this.setPigTicket(() => {
                    location.replace("./my.html");
                })
                break;
        }
    }
    handleCheck(that) {
        if (this.timeout <= 0) {
            this.renderAlert({
                className: "alertGameMiddle",
                type: 'gameover',
                imgsrc: `${baseUrl}tk_bg_over.png`,
                alertWord: '快去猪猪庙看看获得的 “<span class="mark">猪福</span>” 吧！',
                btnword: '进入猪猪庙'
            })
            return;
        }
        if (that.getAttribute("clicked")) {
            this.showcommonAlert({
                word: "这里领取过哦，请前往下一个站点哦~"
            })
            return;
        }
        that.setAttribute("clicked", true);
        fly.post("/index/index/check_pigticket")
            .then(res => {
                if (res.code != 1) {
                    this.showcommonAlert({
                        word: res.msg || '网络错误'
                    })
                    return;
                }
                if (res.result.type == 0) {
                    this.renderAlert({
                        className: "alertGameMiddle",
                        type: 'checkFail',
                        imgsrc: `${baseUrl}tk_bg_cry.png`,
                        alertWord: '<span class="strong">啊偶~</span>这里没有呢~',
                        btnword: '再找找看'
                    })
                    return;
                }
                this.renderAlert({
                    className: "alertGameBig",
                    type: 'checkSuccess',
                    imgsrc: res.result.img,
                    alertWord: '<span class="strong">哇喔！</span>这张符可不是一般人可以拿到的哦',
                    btnword: '收下啦'
                })
                this.data.my_pigticket.push(res.result.type);
            })
    }
    showcommonAlert(params) {
        let html = template('tipTmpl', params);
        this.alertContent.innerHTML = html;
        this.alertWraper.style.display = 'block';
    }
    clockControl() {
        if (this.timer || this.timeout <= 0) {
            clearInterval(this.timer);
            this.timer = null;
            return;
        }
        this.timer = setInterval(() => {
            document.getElementById("clock").innerText = this.timeout + 's';
            if (this.timeout <= 0) {
                clearInterval(this.timer);
                this.timer = null;
                this.renderAlert({
                    className: "alertGameMiddle",
                    type: 'gameover',
                    imgsrc: `${baseUrl}tk_bg_over.png`,
                    alertWord: '快去猪猪庙看看获得的 “<span class="mark">猪福</span>” 吧！',
                    btnword: '进入猪猪庙'
                })
            }
            this.timeout--;
        }, 1000)
    }
    setPigTicket(callback) {
        let payload = `data=${JSON.stringify({pigtickets: this.data.my_pigticket})}`;
        fly.post("/index/index/put_pigticket", payload)
            .then((res) => {
                if (res.code == -1) {
                    this.showcommonAlert({
                        word: res.msg || '网络错误'
                    })
                    return;
                }
                callback && callback();
            })
    }
    audioAutoPlay(id) {
        let audio = document.getElementById(id);

        function play() {
            audio.play();
            document.removeEventListener("touchstart", play, false);
        };
        audio.play();
        document.addEventListener("WeixinJSBridgeReady", function () { //微信
            play();
        }, false);
        document.addEventListener("touchstart", play, false);
    }
}

const indexview = new IndexView();
window.indexview = indexview; // 暴露到全局
window.indexview.ready();